<?php


namespace App\Utils;

use Hyperf\Utils\Arr;

/**
 * Class SignUtils
 * 签名/验签
 *
 * @package App\Utils
 */
class SignUtils {

    public static function makeSign ($arr, $key) {

        // 排除sign参数
        unset($arr['sign']);

        // 字典序
        ksort($arr);

        // 追加key
        $arr['key'] = $key;

        // 拼接
        $string = [];

        foreach ($arr as $k => $v) {
            if ($k != 'sign' && $v !== '' && !is_array($v)) {
                array_push($string, $k . '=' . $v);
            }
        }

        $string = join('&', $string);

        // 哈希并大写
        $sign = strtoupper(md5($string));

        return $sign;
    }

    public static function verifySign ($arr, $secret) {

        $sign = Arr::pull($arr, 'sign');

        return self::makeSign($arr, $secret) == $sign;
    }
}
